<template>
    <div class="page">
		<div class="card chat-shell">
			<ChatRoom ref="roomRef" :startStream="startManusStream" aiAvatar="🧠" userAvatar="🙂" />
		</div>
	</div>
</template>

<script setup lang="ts">
import { ref } from 'vue';
import ChatRoom from '../components/ChatRoom.vue';
import { useSeo } from '../composables/useSeo';

const roomRef = ref<InstanceType<typeof ChatRoom> | null>(null);
useSeo({ title: 'AI 超级智能体 - 步骤化对话', description: '步骤化执行与工具编排，SSE 流式输出', keywords: '超级智能体, AI, SSE, 工具编排' });

// 启动 SSE：调用 /ai/manus/chat?message=
function startManusStream(message: string) {
	const url = new URL('http://localhost:8123/api/ai/manus/chat');
	url.searchParams.set('message', message);

	const es = new EventSource(url.toString());
	roomRef.value?.append('ai', '');

	const onMessage = (ev: MessageEvent) => {
		let data = ev.data || '';
		if (data === '[DONE]') {
			cleanup();
			roomRef.value?.endStream();
			return;
		}
		// 超级智能体：服务端一次步骤完成响应一次，额外追加一个换行
		roomRef.value?.appendAiChunk(data + "\n");
	};

	const onError = () => {
		cleanup();
		roomRef.value?.endStream();
	};

	function cleanup() {
		es.removeEventListener('message', onMessage as any);
		es.removeEventListener('error', onError as any);
		es.close();
	}

	es.addEventListener('message', onMessage as any);
	es.addEventListener('error', onError as any);

	return () => cleanup();
}
</script>

<style scoped>
</style>


